package com.ruoyi.quartz.task;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.bizsys.domain.SmsTask;
import com.ruoyi.bizsys.domain.SmsTemplate;
import com.ruoyi.bizsys.service.IAppUserService;
import com.ruoyi.bizsys.service.ISmsTaskService;
import com.ruoyi.bizsys.service.ISmsTemplateService;
import com.ruoyi.bizsys.service.IVerifyCodeLogService;
import com.ruoyi.market.config.MarketUserConfig;
import com.ruoyi.market.domain.MarketUser;
import com.ruoyi.market.service.IMarketUserService;
import com.ruoyi.market.util.HttpConnetUtil;
import com.ruoyi.market.util.MarketSmsTemplateUtil;
import com.ruoyi.market.util.MarketUserLabel;
import com.ruoyi.market.vo.MarketParamVo;
import com.ruoyi.market.vo.MarketUserVo;
import com.ruoyi.sms.domain.SmsSendData;
import com.ruoyi.system.service.ISysDictDataService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 营销短信任务
 * @author pgc
 * @date: 2021-12-10
 */
@Slf4j
@Component("marketSmsTask")
public class MarketSmsTask {

    @Autowired
    IVerifyCodeLogService iVerifyCodeLogService;

    @Autowired
    IAppUserService appUserService;

    @Autowired
    ISmsTaskService smsTaskService;

    /**
     *  营销短信通知类型
     */
    public static final String SMS_NOTICE_TYPE = "market";

    /**
     *  国别号
     */
    public static final String SMS_COUNTRY_CODE = "+234";

    public static String PARAM_MARK = "#";

    /**
     * 短信间隔天数字典类型
     */
    public static String MARKET_SMS_INTERVAL_TIME ="market_sms_interval_time";

    @Autowired
    ISmsTemplateService smsTemplateService;

    @Autowired
    IMarketUserService marketUserService;

    @Autowired
    ISysDictDataService sysDictDataService;

    @Autowired
    MarketUserConfig marketUserConfig;

    /**
     * 从各个表中获取需要营销的用户信息 生成短信任务
     */
    public void getAppMarketUser(){
        int queryTime = Integer.valueOf(sysDictDataService.selectDictLabel(MARKET_SMS_INTERVAL_TIME,"market_user_select_time"));

        //安装未注册
        MarketParamVo marketParamVo=  new MarketParamVo();
        marketParamVo.setSmsType("register");
        marketParamVo.setCreateTime(getDaysBefore(queryTime));
        //获取未注册的手机号
        List<MarketUserVo> verifyCodeLogList = marketUserService.selectUnregisteredPhone(marketParamVo);
        int result = createRecallAuthorization(verifyCodeLogList);
        log.info("-------- 生成的安装未注册短信任务有  ： " + result + " 条");

        //注册未实名
        List<MarketUserVo> appUserList = marketUserService.selectNoRealNameList(marketParamVo);
        result = createRecallRegisterPwd(appUserList);
        log.info("-------- 生成的注册未实名 短信任务有  ： " + result + " 条");

        //实名成功
        marketParamVo.setCreateTime(getDaysBefore(queryTime));
        List<MarketUserVo> realNameAuthList = marketUserService.selectRealNameAuthList(marketParamVo);
        result = createMarketSmsTask(realNameAuthList, MarketSmsTemplateUtil.RECALL_KYC_SUCCESS);
        log.info("-------- 生成的实名成功未授信的 短信任务有  ： " + result + " 条");

        //实名失败 由于 生日错误、bvn手机号输入错误
        List<MarketUserVo> realNameAuthLogList = marketUserService.selectRealNameAuthLogList(marketParamVo);
        result = createRealNameAuthLogTask(realNameAuthLogList);
        log.info("-------- 生成的实名失败需要营销的 短信任务有  ： " + result + " 条");

        //授信 成功且未提现
        marketParamVo.setApplyStatus(1);
        List<MarketUserVo> creditApplyList = marketUserService.selectCreditApplyList(marketParamVo);
        result = createMarketSmsTask(creditApplyList,MarketSmsTemplateUtil.RECALL_CREDIT_SUCCESS);
        log.info("-------- 生成的授信 成功且未提现 需要营销的 短信任务有  ： " + result + " 条");

        //授信 非风控规则导致失败 apply_status in (10,11)
        List<MarketUserVo> creditApplyFailedList = marketUserService.selectCreditApplyByRiskList(marketParamVo);
        result = createMarketSmsTask(creditApplyFailedList,MarketSmsTemplateUtil.RECALL_KYCFAILED);
        log.info("-------- 生成的授信 非风控规则导致失败 需要营销的 短信任务有  ： " + result + " 条");

        //绑卡 成功
        List<MarketUserVo> custBankCardList = marketUserService.selectCustBankCardList(marketParamVo);
        result = createMarketSmsTask(custBankCardList,MarketSmsTemplateUtil.RECALL_CARDBING_SUCCESS);
        log.info("-------- 生成的绑卡 成功 需要营销的 短信任务有  ： " + result + " 条");

        //绑卡失败 需要营销的用户
        int bankCardValidity = Integer.valueOf(sysDictDataService.selectDictLabel("bankCardValidity","bank_card_validity"));
        marketParamVo.setBankCardValidity(bankCardValidity);
        List<MarketUserVo> custBindCardLogList =marketUserService.selectCustBindCardLogList(marketParamVo);
        result = createCustBindCardLogTask(custBindCardLogList);
        log.info("-------- 生成的绑卡失败 需要营销的 短信任务有  ： " + result + " 条");

        //提现 失败需要营销的用户
        List<MarketUserVo> loanOrderList = marketUserService.selectLoanOrderList(marketParamVo);
        result = createLoanOrderTask(loanOrderList);
        log.info("-------- 生成的提现 失败 需要营销的 短信任务有  ： " + result + " 条");

        //提额 后未提现需要营销的用户
//        List<MarketUserVo> increasedLimitLogList = marketUserService.selectIncreasedLimitLogList(marketParamVo);
//        result = createMarketSmsTask(increasedLimitLogList,MarketSmsTemplateUtil.RECALL_INCREASE_DAY3);
//        log.info("-------- 生成的提额 后未提现需要营销的 短信任务有  ： " + result + " 条");
    }

    /**
     * 隔 X 天后再来检查 短信发送后的结果
     */
    public void getMarketSmsSendResult(){
        int queryTime = Integer.valueOf(sysDictDataService.selectDictLabel(MARKET_SMS_INTERVAL_TIME,"market_user_select_time"));
        //获取配置的营销短信结果检查时间
        int intervalTime = Integer.valueOf(sysDictDataService.selectDictLabel(MARKET_SMS_INTERVAL_TIME,"interval_time"));
        //汇总更新
        List<MarketUserVo> allList = new ArrayList<>();
        //安装未注册
        MarketParamVo marketParamVo=  new MarketParamVo();
        marketParamVo.setSmsType("register");
        marketParamVo.setCreateTime(getDaysBefore(queryTime+intervalTime));
        marketParamVo.setEndTime(getDaysBefore(intervalTime));
        //获取未注册的手机号
        List<MarketUserVo> verifyCodeLogList = marketUserService.selectUnregisteredPhone(marketParamVo);
        allList.addAll(verifyCodeLogList);
        log.info("-------- 需要推向营销系统 安装未注册的用户名单有  ： "
                + verifyCodeLogList.size() + " 条 , 总数为 ：" + allList.size() +" 条");

        //注册未实名
        List<MarketUserVo> appUserList = marketUserService.selectNoRealNameList(marketParamVo);
        allList.addAll(appUserList);
        log.info("-------- 需要推向营销系统 注册未实名 的用户名单有  ： "
                + appUserList.size() + " 条, 总数为 ：" + allList.size() +" 条");

        //实名成功
        List<MarketUserVo> realNameAuthList = marketUserService.selectRealNameAuthList(marketParamVo);
        allList.addAll(realNameAuthList);
        log.info("-------- 需要推向营销系统 实名成功未授信的 用户名单有  ： "
                + realNameAuthList.size() + " 条, 总数为 ：" + allList.size() +" 条");

        //实名失败 由于 生日错误、bvn手机号输入错误
        List<MarketUserVo> realNameAuthLogList = marketUserService.selectRealNameAuthLogList(marketParamVo);
        allList.addAll(realNameAuthLogList);
        log.info("-------- 需要推向营销系统 实名失败的 用户名单有  ： "
                + realNameAuthLogList.size() + " 条, 总数为 ：" + allList.size() +" 条");

        //授信 成功且未提现
        marketParamVo.setApplyStatus(1);
        List<MarketUserVo> creditApplyList = marketUserService.selectCreditApplyList(marketParamVo);
        allList.addAll(creditApplyList);
        log.info("-------- 需要推向营销系统 授信 成功且未提现的 用户名单有  ： "
                + realNameAuthLogList.size() + " 条, 总数为 ：" + allList.size() +" 条");

        //授信 非风控规则导致失败 apply_status in (10,11)
        List<MarketUserVo> creditApplyFailedList = marketUserService.selectCreditApplyByRiskList(marketParamVo);
        allList.addAll(creditApplyFailedList);
        log.info("-------- 需要推向营销系统 授信 非风控规则导致失败的 用户名单有  ： "
                + realNameAuthLogList.size() + " 条, 总数为 ：" + allList.size() +" 条");
        //绑卡 成功
        List<MarketUserVo> custBankCardList = marketUserService.selectCustBankCardList(marketParamVo);
        allList.addAll(custBankCardList);
        log.info("-------- 需要推向营销系统 绑卡 成功 的 用户名单有  ： "
                + custBankCardList.size() + " 条, 总数为 ：" + allList.size() +" 条");
        //绑卡失败 需要营销的用户
        //绑卡有效期
        int bankCardValidity = Integer.valueOf(sysDictDataService.selectDictLabel("bankCardValidity","bank_card_validity"));
        marketParamVo.setBankCardValidity(bankCardValidity);
        List<MarketUserVo> custBindCardLogList =marketUserService.selectCustBindCardLogList(marketParamVo);
        allList.addAll(custBindCardLogList);
        log.info("-------- 需要推向营销系统 绑卡失败 的 用户名单有  ： "
                + custBindCardLogList.size() + " 条, 总数为 ：" + allList.size() +" 条");

        //提现 失败需要营销的用户
        List<MarketUserVo> loanOrderList = marketUserService.selectLoanOrderList(marketParamVo);
        allList.addAll(loanOrderList);
        log.info("-------- 需要推向营销系统 提现 失败 的 用户名单有  ： "
                + loanOrderList.size() + " 条, 总数为 ：" + allList.size() +" 条");

        //提额 后未提现需要营销的用户
        List<MarketUserVo> increasedLimitLogList = marketUserService.selectIncreasedLimitLogList(marketParamVo);
        allList.addAll(increasedLimitLogList);
        batchUpdateMarketUser(allList);
        log.info("-------- 需要推向营销系统 提额 后未提现 的 用户名单有  ： "
                + increasedLimitLogList.size() + " 条, 总数为 ：" + allList.size() +" 条");

        /**
         * 向营销系统推送营销用户名单
         * 1、查询出state= 1 的数据
         * 2、推送至营销系统
         * 3、修改这批数据state=2
         */
        MarketParamVo marketParam=  new MarketParamVo();
        marketParam.setCreateTime(getDaysBefore(queryTime+intervalTime));
        marketParam.setEndTime(getDaysBefore(intervalTime));
        marketParam.setState("1");
        List<MarketUser> marketUserList = marketUserService.selectMarketUserByState(marketParam);
        JSONObject jsonParam = marketUserFormatt(marketUserList,"add");

        //推送至营销系统
        if(jsonParam.getJSONArray("data").size()>0){
            String resultInfo = null;
            try {
                resultInfo = HttpConnetUtil.sendPost(marketUserConfig.getMarketUserImportUrl(), jsonParam.toJSONString());
            } catch (Exception e) {
                log.error("--------- 推送至营销系统 异常",e);
            }
            log.info("-------- 营销用户推送至 营销系统： " + resultInfo);
        }
        //推送成功修改这批数据 的状态 将state1 改成state2
        String state2 = "2";
        marketUserService.updateMarketUserState("1",state2);
    }

    /**
     * 将前一天
     * 推送剔除用户至营销系统
     */
    public void pushRejectMarketUser(){
        MarketParamVo marketParam=  new MarketParamVo();
        marketParam.setCreateTime(getDaysBefore(1));
        marketParam.setEndTime(getDaysBefore(0));
        marketParam.setState("3");
        //查询前一天需要剔除的用户
        List<MarketUser> marketUserList = marketUserService.selectRejectMarketUser(marketParam);
        JSONObject jsonParam = marketUserFormatt(marketUserList,"update");
        //推送至营销系统
        if(jsonParam.getJSONArray("data").size()>0){
            String resultInfo = null;
            try {
                resultInfo = HttpConnetUtil.sendPost(marketUserConfig.getMarketUserImportUrl(), jsonParam.toJSONString());
            } catch (Exception e) {
                log.error("--------- 推送至营销系统 异常",e);
            }
            log.info("-------- 营销用户推送至 营销系统： " + resultInfo);
        }
    }

    private int batchUpdateMarketUser(List<MarketUserVo> marketUserVoList) {
        //每批处理的数目
        int batchCount = 1000;
        int batchLastIndex = batchCount;
        List<List<MarketUserVo>> shareList = new ArrayList<>();
        for (int index = 0; index < marketUserVoList.size(); ) {
            if (batchLastIndex >= marketUserVoList.size()) {
                batchLastIndex = marketUserVoList.size();
                shareList.add(marketUserVoList.subList(index, batchLastIndex));
                break;
            } else {
                shareList.add(marketUserVoList.subList(index, batchLastIndex));
                // 设置下一批下标
                index = batchLastIndex;
                batchLastIndex = index + batchCount;
            }
        }
        if (CollectionUtils.isNotEmpty(shareList)) {
            for (List<MarketUserVo> subList : shareList) {
                //循环处理数据
                marketUserService.batchUpdateMarketUser(subList);
            }
        }
        return marketUserVoList.size();
    }

    /**
     * 生成提现 失败需要营销的短信任务
     * @param loanOrderList
     * @return
     */
    private int createLoanOrderTask(List<MarketUserVo> loanOrderList) {
        List<SmsTask> smsTaskList = new ArrayList<>();

        //营销用户信息
        List<MarketUser> marketUserList = new ArrayList<>();

        //提现失败贷款取消_卡单 短信模板
        SmsSendData smsData = SmsSendData.builder()
                .noticeType(SMS_NOTICE_TYPE)
                .build();
       for(int i=0; i<loanOrderList.size(); i++) {
            MarketUserVo marketUserVo = loanOrderList.get(i);
            SmsTask smsTask = new SmsTask();
            smsTask.setCountryCode(SMS_COUNTRY_CODE);
            smsTask.setPhone(marketUserVo.getPhoneNumber());
            smsTask.setNoticeType(SMS_NOTICE_TYPE);
            JSONObject smsJson = new JSONObject();
            //提现	失败	贷款取消-卡单
            if(marketUserVo.getLoanStatus().equals("10")){
                smsData.setSmsType(MarketSmsTemplateUtil.RECALL_WITHDRAWFAILED_CANCLE);
                smsJson.put("credit_line",marketUserVo.getCreditLine()==null ? 0: marketUserVo.getCreditLine());
                marketUserVo.setUserLabel(MarketUserLabel.WITHDRAWAL_FAILED);
            }
            //失败	未找到
            else if(marketUserVo.getLoanStatus().equals("5") &&
                    marketUserVo.getRemark().equals("{\"message\":\"Transfer not found\",\"status\":false}")){
                smsData.setSmsType(MarketSmsTemplateUtil.RECALL_WITHDRAWFAILED_NOTFOUND);
                smsJson.put("amt", marketUserVo.getCreditLine().subtract(marketUserVo.getLoanQuota()));
                marketUserVo.setUserLabel(MarketUserLabel.WITHDRAWAL_FAILED);
            }
            //失败	不能发起
            else if(marketUserVo.getLoanStatus().equals("5") &&
                    marketUserVo.getRemark().equals("You cannot initiate third party payouts at this time")){
                smsData.setSmsType(MarketSmsTemplateUtil.RECALL_WITHDRAWFAILED_CANTSTART);
                smsJson.put("amt", marketUserVo.getCreditLine().subtract(marketUserVo.getLoanQuota()));
                marketUserVo.setUserLabel(MarketUserLabel.WITHDRAWAL_FAILED);
            }
            //失败	发生错误
            else if(marketUserVo.getLoanStatus().equals("5") &&
                    marketUserVo.getRemark().equals("Error Occurred")){
                smsData.setSmsType(MarketSmsTemplateUtil.RECALL_WITHDRAWFAILED_ERROR);
                smsJson.put("amt", marketUserVo.getCreditLine().subtract(marketUserVo.getLoanQuota()));
                marketUserVo.setUserLabel(MarketUserLabel.WITHDRAWAL_FAILED);
            }else if(marketUserVo.getLoanStatus().equals("5") &&
                    marketUserVo.getRemark().equals("Your balance is not enough to fulfil this request")){
                smsData.setSmsType(MarketSmsTemplateUtil.RECALL_WITHDRAWFAILED_NOTSUFFICIENTFUNDS);
                marketUserVo.setUserLabel(MarketUserLabel.WITHDRAWAL_FAILED);
            }

            smsData.setSmsParam(smsJson);
            JSONObject smsParam = getSmsContnet(smsData);
            smsTask.setSmsType(smsData.getSmsType());
            smsTask.setContent(smsParam.getString("content"));
            smsTask.setTemplateId(smsParam.getString("templateId"));
           if(null !=smsTask.getPhone() && null !=smsTask.getSmsType()){
               smsTaskList.add(smsTask);
           }
            MarketUser marketUser = setMarketUserPerporty(loanOrderList.get(i));
            marketUserList.add(marketUser);
            if(i == 999 || i== loanOrderList.size()-1){
//                smsTaskService.batchAdd(smsTaskList);
//                smsTaskList=  new ArrayList<>();

                marketUserService.batchAddMarketUser(marketUserList);
                marketUserList = new ArrayList<>();
            }
        }
        return loanOrderList.size();
    }

    /**
     * 绑卡失败 生成营销短信任务
     * @param custBindCardLogList
     * @return
     */
    private int createCustBindCardLogTask(List<MarketUserVo> custBindCardLogList) {
        List<SmsTask> smsTaskList = new ArrayList<>();

        //营销用户信息
        List<MarketUser> marketUserList = new ArrayList<>();

        SmsSendData smsData = SmsSendData.builder()
                .noticeType(SMS_NOTICE_TYPE)
                .build();
        for(int i=0; i<custBindCardLogList.size(); i++) {
            MarketUserVo marketUserVo = custBindCardLogList.get(i);
            SmsTask smsTask = new SmsTask();
            smsTask.setCountryCode(SMS_COUNTRY_CODE);
            smsTask.setPhone(marketUserVo.getPhoneNumber());
            smsTask.setNoticeType(SMS_NOTICE_TYPE);
            JSONObject smsJson = new JSONObject();
            //卡失效
            log.info("-------:" + marketUserVo.getRemark());
            if(marketUserVo.getBindTransStatus().equals("0") && (
                    marketUserVo.getRemark().toLowerCase().equals("approved")
                    || marketUserVo.getRemark().toLowerCase().equals("approved by financial institution") )){
                smsData.setSmsType(MarketSmsTemplateUtil.RECALL_CARDFAILED);
                marketUserVo.setUserLabel(MarketUserLabel.CARD_EXPIRED);
            }else if(marketUserVo.getBindTransStatus().equals("5")){//重复绑卡 系统已存在
                smsData.setSmsType(MarketSmsTemplateUtil.RECALL_CARDEXIST);
                smsJson.put("cardNumber",marketUserVo.getCardNumber());
                marketUserVo.setUserLabel(MarketUserLabel.CARD_EXIST);
            }else if(marketUserVo.getBindTransStatus().equals("7")){//重复绑卡 本人已存在
                smsData.setSmsType(MarketSmsTemplateUtil.RECALL_CARDREUSE);
                smsJson.put("cardNumber",marketUserVo.getCardNumber());
                marketUserVo.setUserLabel(MarketUserLabel.CARD_INVALID);
            }else if(marketUserVo.getRemark().toLowerCase().equals("insufficient funds")){//余额不足
                smsData.setSmsType(MarketSmsTemplateUtil.RECALL_CARDNOTSUFFICIENTFUDS);
                marketUserVo.setUserLabel(MarketUserLabel.CARD_INSUFFICIENT);
            }
            smsData.setSmsParam(smsJson);
            JSONObject smsParam = getSmsContnet(smsData);
            smsTask.setSmsType(smsData.getSmsType());
            smsTask.setContent(smsParam.getString("content"));
            smsTask.setTemplateId(smsParam.getString("templateId"));
            if(null !=smsTask.getPhone() && null !=smsTask.getSmsType()){
                smsTaskList.add(smsTask);
            }
            MarketUser marketUser = setMarketUserPerporty(marketUserVo);
            marketUserList.add(marketUser);
            if(i == 999 || i== custBindCardLogList.size()-1){
//                smsTaskService.batchAdd(smsTaskList);
//                smsTaskList=  new ArrayList<>();

                marketUserService.batchAddMarketUser(marketUserList);
                marketUserList = new ArrayList<>();
            }
        }
        return custBindCardLogList.size();
    }

    /**
     * 生成营销短信任务
     * 1、绑卡 成功需要营销
     * 2、实名成功
     * 3、授信成功
     * 4、提额 未提现
     * 5、授信 非风控规则导致失败
     */
    public int createMarketSmsTask(List<MarketUserVo> marketUserVoList,String type){
        List<SmsTask> smsTaskList = new ArrayList<>();
        //营销用户信息
        List<MarketUser> marketUserList = new ArrayList<>();
        SmsSendData smsData = SmsSendData.builder()
                .smsType(type)
                .noticeType(SMS_NOTICE_TYPE)
                .build();

        for(int i=0; i<marketUserVoList.size(); i++) {
            MarketUserVo marketUserVo = marketUserVoList.get(i);
            JSONObject smsJson = new JSONObject();
            switch (type){
                case MarketSmsTemplateUtil.RECALL_KYC_SUCCESS:// 实名成功
                    smsJson.put("lastName",marketUserVo.getLastName()==null?"linkCredit":marketUserVo.getLastName());
                    marketUserVo.setUserLabel(MarketUserLabel.VERIFED_BUT_NOT_APPLIED);
                    break;
                case MarketSmsTemplateUtil.RECALL_CREDIT_SUCCESS:// 授信成功
                    smsJson.put("lastName",marketUserVo.getLastName()==null?"linkCredit":marketUserVo.getLastName());
                    marketUserVo.setUserLabel(MarketUserLabel.APPLICATION_SUCCESS_NO_CARD_BOUND);
                    break;
                case MarketSmsTemplateUtil.RECALL_CARDBING_SUCCESS:// 绑卡成功
                    smsJson.put("lastName",marketUserVo.getLastName()==null?"linkCredit":marketUserVo.getLastName());
                    marketUserVo.setUserLabel(MarketUserLabel.CARD_BIND_SUCCESS_NO_WITHDRAWAL);
                    break;
//                case MarketSmsTemplateUtil.RECALL_INCREASE_DAY3:// 提额 未提现
//                    smsJson.put("credit_line",marketUserVo.getCreditLine());
//                    marketUserVo.setUserLabel(MarketUserLabel.CREDIT_LIMIT_RAISED_UN_WITHDRAWAL);
//                    break;
                case MarketSmsTemplateUtil.RECALL_KYCFAILED:// 授信失败
                    marketUserVo.setUserLabel(MarketUserLabel.CREDIT_LIMIT_FAILED);
                    break;
            }
            smsData.setSmsParam(smsJson);
            JSONObject smsParam = getSmsContnet(smsData);

            SmsTask smsTask = new SmsTask();
            smsTask.setCountryCode(SMS_COUNTRY_CODE);
            smsTask.setPhone(marketUserVo.getPhoneNumber());
            smsTask.setSmsType(type);
            smsTask.setContent(smsParam.getString("content"));
            smsTask.setNoticeType(SMS_NOTICE_TYPE);
            smsTask.setTemplateId(smsParam.getString("templateId"));
            if(null !=smsTask.getPhone() && null !=smsTask.getSmsType()){
                smsTaskList.add(smsTask);
            }
            MarketUser marketUser = setMarketUserPerporty(marketUserVo);
            marketUserList.add(marketUser);
            if(i == 999 || i== marketUserVoList.size()-1){
//                smsTaskService.batchAdd(smsTaskList);
//                smsTaskList=  new ArrayList<>();

                marketUserService.batchAddMarketUser(marketUserList);
                marketUserList = new ArrayList<>();
            }
        }
        return marketUserVoList.size();
    }

    /**
     *
     * @param realNameAuthLogList
     * @return
     */
    private int createRealNameAuthLogTask(List<MarketUserVo> realNameAuthLogList) {
        List<SmsTask> smsTaskList = new ArrayList<>();

        //营销用户信息
        List<MarketUser> marketUserList = new ArrayList<>();
        SmsSendData smsData_bvn = SmsSendData.builder()
                .smsType(MarketSmsTemplateUtil.RECALL_DOB_ERROR)
                .noticeType(SMS_NOTICE_TYPE)
                .build();
        JSONObject smsParam_bvn = getSmsContnet(smsData_bvn);

        SmsSendData smsData_phone = SmsSendData.builder()
                .smsType(MarketSmsTemplateUtil.RECALL_BVNERROR)
                .noticeType(SMS_NOTICE_TYPE)
                .build();
        JSONObject smsParam_phone = getSmsContnet(smsData_phone);
        for(int i=0; i<realNameAuthLogList.size(); i++) {
            MarketUserVo marketUserVo = realNameAuthLogList.get(i);
            SmsTask smsTask = new SmsTask();
            smsTask.setCountryCode(SMS_COUNTRY_CODE);
            smsTask.setPhone(marketUserVo.getPhoneNumber());
            smsTask.setNoticeType(SMS_NOTICE_TYPE);
            if(marketUserVo.getErrorMsg().equals("Real name check failed (by birthday). ")){
                smsTask.setSmsType(MarketSmsTemplateUtil.RECALL_DOB_ERROR);
                smsTask.setContent(smsParam_bvn.getString("content"));
                smsTask.setTemplateId(smsParam_bvn.getString("templateId"));

                marketUserVo.setUserLabel(MarketUserLabel.UNVERIFIED_DATE_OF_BIRTH_INCORRECT);
            }else if(marketUserVo.getErrorMsg().equals("Verification phone number failed.")) {
                smsTask.setSmsType(MarketSmsTemplateUtil.RECALL_BVNERROR);
                smsTask.setContent(smsParam_phone.getString("content"));
                smsTask.setTemplateId(smsParam_phone.getString("templateId"));

                marketUserVo.setUserLabel(MarketUserLabel.VERIFICATION_FAILED_BVN_BOUND_NUMBER_INCORRECT);
            }
//            log.info("--------- :" + smsTask.getPhone());
            if(null !=smsTask.getPhone() && null !=smsTask.getSmsType()){
                smsTaskList.add(smsTask);
            }


            MarketUser marketUser = setMarketUserPerporty(marketUserVo);
            marketUserList.add(marketUser);
            if(i == 999 || i== realNameAuthLogList.size()-1){
//                smsTaskService.batchAdd(smsTaskList);
//                smsTaskList=  new ArrayList<>();

                marketUserService.batchAddMarketUser(marketUserList);
                marketUserList = new ArrayList<>();
            }
        }
        return realNameAuthLogList.size();
    }

    //安装未注册 生成短信任务
    public int createRecallAuthorization(List<MarketUserVo> verifyCodeLogList) {
        //短信任务集合
        List<SmsTask> smsTaskList = new ArrayList<>();
        //营销用户名单集合
        List<MarketUser> marketUserList = new ArrayList<>();
        SmsSendData smsData = SmsSendData.builder()
                .smsType(MarketSmsTemplateUtil.RECALL_INSTALL_REGISTER)
                .noticeType(SMS_NOTICE_TYPE)
                .build();
        JSONObject smsParam = getSmsContnet(smsData);
        for(int i=0; i<verifyCodeLogList.size(); i++) {
            SmsTask smsTask = new SmsTask();
            smsTask.setCountryCode(SMS_COUNTRY_CODE);
            smsTask.setPhone(verifyCodeLogList.get(i).getPhoneNumber()
                    .substring(verifyCodeLogList.get(i).getPhoneNumber().length()-11));
            smsTask.setSmsType(MarketSmsTemplateUtil.RECALL_INSTALL_REGISTER);
            smsTask.setContent(smsParam.getString("content"));
            smsTask.setNoticeType(SMS_NOTICE_TYPE);
            smsTask.setTemplateId(smsParam.getString("templateId"));
            if(null !=smsTask.getPhone() && null !=smsTask.getSmsType()){
                smsTaskList.add(smsTask);
            }

            //组装营销用户信息
            MarketUser marketUser = new MarketUser();
            marketUser.setPhoneNumber(verifyCodeLogList.get(i).getPhoneNumber()
                    .substring(verifyCodeLogList.get(i).getPhoneNumber().length()-11));
            marketUser.setUserLabel(MarketUserLabel.UNREGISTERED);
            marketUser.setState("0");
            marketUserList.add(marketUser);
            if(i == 999 || i== verifyCodeLogList.size()-1){
//                smsTaskService.batchAdd(smsTaskList);
//                smsTaskList=  new ArrayList<>();

                marketUserService.batchAddMarketUser(marketUserList);
                marketUserList = new ArrayList<>();
            }
        }
        return verifyCodeLogList.size();
    }

    //注册成功有密码/无密码 生成短信任务
    public int createRecallRegisterPwd(List<MarketUserVo> appUserList) {
        List<SmsTask> smsTaskList = new ArrayList<>();
        //营销用户名单集合
        List<MarketUser> marketUserList = new ArrayList<>();

        SmsSendData smsData_pdw = SmsSendData.builder()
                .smsType(MarketSmsTemplateUtil.RECALL_REGISTER_PWD)
                .noticeType(SMS_NOTICE_TYPE)
                .build();
        JSONObject smsParam_pwd = getSmsContnet(smsData_pdw);
        SmsSendData smsData_nopwd = SmsSendData.builder()
                .smsType(MarketSmsTemplateUtil.RECALL_REGISTER_NOPWD)
                .noticeType(SMS_NOTICE_TYPE)
                .build();
        JSONObject smsParam_nopwd = getSmsContnet(smsData_nopwd);
        for(int i=0; i<appUserList.size(); i++){
            //组装营销用户信息
            MarketUser marketUser = new MarketUser();

            SmsTask smsTask = new SmsTask();
            smsTask.setCountryCode(SMS_COUNTRY_CODE);
            smsTask.setPhone(appUserList.get(i).getPhoneNumber());
            if(appUserList.get(i).getPassword() !=null) {
                smsTask.setSmsType(MarketSmsTemplateUtil.RECALL_REGISTER_PWD);
                smsTask.setContent(smsParam_pwd.getString("content"));
                smsTask.setTemplateId(smsParam_pwd.getString("templateId"));

                marketUser.setUserLabel(MarketUserLabel.REGISTERED_NOT_VERIFIED);
            }else{
                smsTask.setSmsType(MarketSmsTemplateUtil.RECALL_REGISTER_NOPWD);
                smsTask.setContent(smsParam_nopwd.getString("content"));
                smsTask.setTemplateId(smsParam_nopwd.getString("templateId"));

                marketUser.setUserLabel(MarketUserLabel.REGISTERED_NO_PASSWORD);
            }
            smsTask.setNoticeType(SMS_NOTICE_TYPE);
            smsTaskList.add(smsTask);


            marketUser.setUserId(appUserList.get(i).getUserId());
            marketUser.setPhoneNumber(appUserList.get(i).getPhoneNumber());
            marketUser.setState("0");
            marketUserList.add(marketUser);

            if(i == 999 || i== appUserList.size()-1){
//                smsTaskService.batchAdd(smsTaskList);
//                smsTaskList=  new ArrayList<>();

                marketUserService.batchAddMarketUser(marketUserList);
                marketUserList = new ArrayList<>();
            }
        }
        return appUserList.size();
    }

    /**
     * 推送营销系统用户数据拼接
     * @param marketUserVoList
     * @return
     */
    public JSONObject marketUserFormatt(List<MarketUser> marketUserVoList,String type){
        JSONObject jsonParam = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        for(MarketUser marketUser : marketUserVoList){
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("userName",marketUser.getLastName());
            jsonObject.put("callPhone",marketUser.getPhoneNumber());
            jsonObject.put("bvnPhone",marketUser.getPhoneNumberBvn());
            jsonObject.put("userId",marketUser.getUserId());
            jsonObject.put("quota",marketUser.getCreditLine());
            jsonObject.put("custNo",marketUser.getCustNo());
            jsonObject.put("usedLimit",marketUser.getLoanQuota());
            jsonObject.put("userLabel",marketUser.getUserLabel());
            jsonObject.put("gender",marketUser.getGender());
            jsonObject.put("birthday",marketUser.getBirthday());
            jsonObject.put("occupation",marketUser.getOccupation());
            //本次提额额度
            jsonObject.put("increasedLimit",marketUser.getIncreasedLimit());
            jsonArray.add(jsonObject);
        }
        jsonParam.put("requestType",type);
        jsonParam.put("data",jsonArray);
        return jsonParam;
    }

    //营销用户信息赋值
    public MarketUser setMarketUserPerporty(MarketUserVo marketUserVo){
        //组装营销用户信息
        MarketUser marketUser = new MarketUser();
        marketUser.setUserId(marketUserVo.getUserId());
        marketUser.setPhoneNumber(marketUserVo.getPhoneNumber());
        marketUser.setPhoneNumberBvn(marketUserVo.getPhoneNumberBvn());
        marketUser.setCreditLine(marketUserVo.getCreditLine());
        marketUser.setLoanQuota(marketUserVo.getLoanQuota());
        marketUser.setCustNo(marketUserVo.getCustNo());
        marketUser.setCardNumber(marketUserVo.getCardNumber());
        marketUser.setLastName(marketUserVo.getLastName());
        marketUser.setUserLabel(marketUserVo.getUserLabel());
        marketUser.setRemark(marketUserVo.getRemark());
        marketUser.setState("0");
        marketUser.setBirthday(marketUserVo.getBirthday());
        marketUser.setOccupation(marketUserVo.getOccupation());
        marketUser.setGender(marketUserVo.getGender());
        //本次提额额度
        marketUser.setIncreasedLimit(marketUserVo.getIncreasedLimit());
        return marketUser;
    }

    //获取 X+1 天前的23:00:00
    public static Date getDaysBefore(int intervalTime) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        Calendar now = Calendar.getInstance();
        now.setTime(date);
        now.add(Calendar.DAY_OF_MONTH, -(intervalTime+1));
        String queryTime = sdf.format(now.getTime()) + " 23:00:00";
        Date dateTime = null;
        try {
            dateTime = simpleDateFormat.parse(queryTime);
        } catch (ParseException e) {
            log.error("----获取前三天的时间：", e);
        }
        return dateTime;
    }

    /**
     * 短信任务生成
     */
    public JSONObject getSmsContnet(SmsSendData smsData) {
        JSONObject jsonObject = new JSONObject();
        SmsTemplate smsTemplate = new SmsTemplate();
        smsTemplate.setNoticeType(smsData.getNoticeType());
        smsTemplate.setSmsType(smsData.getSmsType());
        smsTemplate.setState("1");
        List<SmsTemplate> smsTemplateList = smsTemplateService.selectSmsTemplateList(smsTemplate);
        String content = smsTemplateList.get(0).getTemplateContent();

        if (content.contains(PARAM_MARK)) {
            content = replaceTemplateParams(content, smsData.getSmsParam());
        }
        jsonObject.put("content",content);
        jsonObject.put("templateId",smsTemplateList.get(0).getTemplateId());
        return jsonObject;
    }

    protected String replaceTemplateParams(String templateContent, JSONObject dataJson) {
        String smsContent = templateContent;

        Iterator<String> iterator = (Iterator<String>) dataJson.keySet().iterator();
        while (iterator.hasNext()) {
            String key = iterator.next();
            String value = dataJson.getString(key);
            if (smsContent.contains(key)) {
                smsContent = smsContent.replace(PARAM_MARK + key + PARAM_MARK, value);
            }
        }
        return smsContent;
    }


    /**
     * 获取 还款未提现的用户数据
     * type 查询条件类型，0： T+6  1:指定查询时间段
     * isSend 是否发送短信 0：是  1：否
     */
    public void getRepaymentNotWithdrawn(String type,String isSend){
        MarketParamVo marketParamVo = new MarketParamVo();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //如果是T+6
        if(type.equals("0")){
            Date date = new Date();
            Calendar now = Calendar.getInstance();
            now.setTime(date);
            try {
                now.add(Calendar.DAY_OF_MONTH, -(6+1));
                marketParamVo.setCreateTime(sdf.parse(sdf.format(now.getTime())));
                now.setTime(date);
                now.add(Calendar.DAY_OF_MONTH, -6);
                marketParamVo.setEndTime(sdf.parse(sdf.format(now.getTime())));
            } catch (ParseException e) {
                log.error("------- 拼接 还款未提现 查询时间区间 异常 " ,e);
            }
        }else{
            //查询时间区间
            String beginTime = sysDictDataService.
                    selectDictLabel(MARKET_SMS_INTERVAL_TIME,"Repayment_Not_Withdrawn_beginTime");
            String endTime = sysDictDataService.
                    selectDictLabel(MARKET_SMS_INTERVAL_TIME,"Repayment_Not_Withdrawn_endTime");
            try {
                marketParamVo.setCreateTime(sdf.parse(beginTime));
                marketParamVo.setEndTime(sdf.parse(endTime));
            } catch (ParseException e) {
                log.error("------- 拼接 还款未提现 查询时间区间 异常 " ,e);
            }
        }
        List<MarketUserVo> marketUserVoList = marketUserService.getRepaymentNotWithdrawn(marketParamVo);
        createRepaymentNotWithdrawnSms(marketUserVoList,isSend);
        log.info("--------- 还款未提现 取数结束 ， 取数区间 ："
                + sdf.format(marketParamVo.getCreateTime()) +"----" +marketParamVo.getEndTime()
        +" ----- isSend :" + isSend);
    }

    /**
     * 生成还款未提现营销短信
     * @param marketUserVoList
     * @param isSend 是否需要发送短信
     * @return
     */
    public int createRepaymentNotWithdrawnSms(List<MarketUserVo> marketUserVoList,String isSend) {
        List<SmsTask> smsTaskList = new ArrayList<>();
        //营销用户名单集合
        List<MarketUser> marketUserList = new ArrayList<>();
        SmsSendData smsData = SmsSendData.builder()
                .smsType(MarketSmsTemplateUtil.RECALL_RE_LOAN)
                .noticeType(SMS_NOTICE_TYPE)
                .build();

        for(int i=0; i<marketUserVoList.size(); i++){
            MarketUserVo marketUserVo = marketUserVoList.get(i);

            //组织营销短信
            SmsTask smsTask = new SmsTask();
            smsTask.setCountryCode(SMS_COUNTRY_CODE);
            smsTask.setPhone(marketUserVo.getPhoneNumber());
            smsTask.setSmsType(MarketSmsTemplateUtil.RECALL_RE_LOAN);
            JSONObject smsJson = new JSONObject();
            smsJson.put("lastname", marketUserVo.getLastName());
            smsJson.put("amount", marketUserVo.getCreditLine().subtract(marketUserVo.getLoanQuota()));
            smsData.setSmsParam(smsJson);
            JSONObject smsParam = getSmsContnet(smsData);
            smsTask.setContent(smsParam.getString("content"));
            smsTask.setTemplateId(smsParam.getString("templateId"));
            smsTask.setNoticeType(SMS_NOTICE_TYPE);
            if(null !=smsTask.getPhone()){
                smsTaskList.add(smsTask);
            }
            //组装营销用户信息
            MarketUser marketUser = new MarketUser();
            marketUser.setUserLabel(MarketUserLabel.NO_WITHDRAW_AFTER_REPAYMENT);
            marketUser.setUserId(marketUserVo.getUserId());
            marketUser.setPhoneNumber(marketUserVo.getPhoneNumber());
            marketUser.setState("0");
            marketUserList.add(marketUser);

            if(i == 999 || i== marketUserVoList.size()-1){
                if(isSend.equals("0")){
                    smsTaskService.batchAdd(smsTaskList);
                    smsTaskList=  new ArrayList<>();
                }
                marketUserService.batchAddMarketUser(marketUserList);
                marketUserList = new ArrayList<>();
            }
        }
        return marketUserVoList.size();
    }

}
